﻿using CarEdge.Infrastructure.Attr;
using CarEdge.Infrastructure.Dto.Request.Dic;
using CarEdge.Infrastructure.Dto.Response;
using CarEdge.Infrastructure.Dto.Response.Dic;
using CarEdge.Infrastructure.EFCore.MySql;
using CarEdge.Infrastructure.IOC;
using CarEdge.Infrastructure.IOC.Dic;
using CarEdge.Service.EFCore;
using CarEdge.Service.Interface.Dic;
using Crm.Infrastructure.Tools;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CarEdge.Service.Instance.Dic
{
    /// <summary>
    ///字典管理 
    /// </summary>
    [Inject_]
    public class Dic_Service : Base_Service, I_Dic_Service
    {
        private readonly Dic_IOC _dic_IOC;
        private readonly Login_IOC _login_IOC;

        public Dic_Service(Dic_IOC dic_IOC,Login_IOC login_IOC)
        {
            _dic_IOC = dic_IOC;
            _login_IOC = login_IOC;

        }
        /// <summary>
        /// 新增字典
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Add_Dictionary(Dic_Request_Dto dto)
        {
            if(!await _dic_IOC._dictionary_Type_EFCore.QueryAll(d => d.DtId == dto.type).AnyAsync())
            {
                return Result(0, "字典类型不正确");
            }
            SysDictionary sysDictionary = new SysDictionary()
            {
                DId = Config.GUID(),
                DName = dto.name,
                DAuthor = dto.author,
                DCreateTime = DateTime.Now,
                DDtId = dto.type,
                DExplain = dto.explain,
                DValue = dto.value,
                DUserCount = 0,
            };
            _dic_IOC._dictionary_EFCore.Add(sysDictionary);
            var result=await _dic_IOC._dictionary_EFCore.SaveChangesAsync();
            return Result(result);
        }
        /// <summary>
        /// 新增字典类别
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Add_Dictionary_Type(Dic_Request_Dto dto)
        {

            SysDictionaryType sysDictionaryType = new SysDictionaryType()
            {
                DtId = Config.GUID(),
                DtName = dto.name,
                DtKey = dto.gjkey,
                DtValue = dto.value,
                
                DtAuthor = dto.author,
                DtCreateTime = DateTime.Now,
                DtUpdateAuthor=null,
                DtCount = 0,
                DtDesc =null,
                DtExplain = dto.explain,
               
               
            };

            _dic_IOC._dictionary_Type_EFCore.Add(sysDictionaryType);
          var result=await  _dic_IOC._dictionary_Type_EFCore.SaveChangesAsync();
            return Result(result);
        }

        /// <summary>
        /// 删除字典
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Delete_Dictionarys(IEnumerable<string?>? ids)
        {
            var iq = _dic_IOC._dictionary_EFCore.QueryAll(d => ids!.Contains(d.DId) && d.DUserCount == 0);
            _dic_IOC._dictionary_EFCore.DeleteRange(iq);
            var result = await _dic_IOC._dictionary_EFCore.SaveChangesAsync();
            return Result(result); 
        }
        /// <summary>
        /// 删除字典类型
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Delete_Dic_Types(IEnumerable<string?>? ids)
        {
            var iq = _dic_IOC._dictionary_Type_EFCore.QueryAll(d => ids!.Contains(d.DtId) && d.DtCount == 0);
            _dic_IOC._dictionary_Type_EFCore.DeleteRange(iq);
            var result = await  _dic_IOC._dictionary_Type_EFCore.SaveChangesAsync();
            return Result(result);
        }

        /// <summary>
        /// 编辑修改字典信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Edit_Dic(Dic_Request_Dto dto)
        {
            var iq=await _dic_IOC._dictionary_EFCore.QueryAll(d=>d.DId==dto.id).SingleAsync();
            iq.DName=dto.name;
            iq.DUpdateAuthor=dto.Up_author;
            iq.DValue=dto.value;
            iq.DExplain=dto.explain;

            _dic_IOC._dictionary_EFCore.Update(iq);
            var result = await _dic_IOC._dictionary_EFCore.SaveChangesAsync();
            return Result(result);
        }

        /// <summary>
        /// 获取字典列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_AllDic_Type(int page = 1, int limit = 10, string key = "")
        {
            var iq = _dic_IOC._dictionary_Type_EFCore.QueryAll(out int total, page, limit, false, o => o.DtCreateTime, d => d.DtName!.Contains(key) || d.DtKey!.Contains(key) || d.DtValue!.Contains(key));


            var data = await iq.Select(d => new Dictionary_Type_Response_DTO
            {
                id = d.DtId,
                name = d.DtName,
                author = d.DtAuthor,//数据库存储的是ID 
                Up_author = d.DtUpdateAuthor,//修改人ID
                explain = d.DtExplain,
                key = d.DtKey,
                time = d.DtCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                value = d.DtValue,
               
            }).ToListAsync();

            //查询出来的数据在内存中 占用空间一般来说非常小
            var uids = data.Select(d => d.author).ToList();
            uids.AddRange(data.Select(d => d.Up_author).ToList());
            var users = await _login_IOC._sys_User_EFCore.QueryAll(d => uids.Contains(d.Uid)).ToListAsync();

            var dtid = data.Select(d => d.id).ToList();

            var did =await _dic_IOC._dictionary_EFCore.QueryAll(d => dtid.Contains(d.DDtId)).ToListAsync();

            data.ForEach(d =>
            {
                d.count=did.Where(e=>e.DDtId==d.id).Count();
                d.author = users.Where(e => e.Uid == d.author).SingleOrDefault()?.Uname;
                d.Up_author = users.Where(e => e.Uid == d.Up_author).SingleOrDefault()?.Uname;
            });
            return Result(1, "ok", new
            {
                total,
                data
            });
        }
        /// <summary>
        /// 获取字典，根据类别Key  [keys]
        /// </summary>
        /// <param name="strings"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Dictionary_ByKey(IEnumerable<string?>? keys)
        {
            var types=await _dic_IOC._dictionary_Type_EFCore.QueryAll(d=>keys!.Contains(d.DtKey)).ToListAsync();

            var ids=types.Select(d=>d.DtId).ToList();

            var data = await _dic_IOC._dictionary_EFCore.QueryAll(d => ids.Contains(d.DDtId!)).Select(d => new
             Dictionary_Response_Dto
            {
                id = d.DId,
                dtid = d.DDtId,
                name = d.DName,
                value = d.DValue,
            }).ToListAsync();

            data.ForEach(d =>
            {
                d.key = types.Where(e => e.DtId == d.dtid).SingleOrDefault()?.DtKey;
            });
            return Result(1, "ok", data.OrderBy(d => d.value));
        }

        /// <summary>
        /// 获取单个字典类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Get_Single_Dic_Type(string id)
        {
            var iq = _dic_IOC._dictionary_Type_EFCore.QueryAll(d => d.DtId == id);
            if(!await iq.AnyAsync())
            {
                return Result(0, "参数错误");
            }

            var data = iq.Select(d => new Dictionary_Type_Response_DTO
            {
                id=d.DtId,
                name=d.DtName,
                author=d.DtAuthor,
                Up_author=d.DtUpdateAuthor,
                explain=d.DtExplain,
                key=d.DtKey,
                time=d.DtCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                value=d.DtValue,
                count=d.DtCount
            }).Single();
            var children = await _dic_IOC._dictionary_EFCore.QueryAll(d => d.DDtId == id).Select(d => new Dictionary_Response_Dto
            {
                id = d.DId,
                name=d.DName,
                author=d.DAuthor,
                update_author=d.DUpdateAuthor,
                explain = d.DExplain,
                time = d.DCreateTime!.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                value = d.DValue,
                useCount = d.DUserCount ?? 0
            }).ToListAsync();

            var uids = children.Select(d => d.author).ToList();
            uids.AddRange(children.Select(d => d.update_author).ToList());
            uids.Add(data.author);
            uids.Add(data.Up_author);

            var users = await _login_IOC._sys_User_EFCore.QueryAll(d => uids.Contains(d.Uid)).ToListAsync();

            children.ForEach(d =>
            {
                d.author = users.Where(e => e.Uid == d.author).SingleOrDefault()?.Uname;
                d.update_author = users.Where(e => e.Uid == d.update_author).SingleOrDefault()?.Uname;
            });

            data.author = users.Where(e => e.Uid == data.author).SingleOrDefault()?.Uname;
            data.Up_author = users.Where(e => e.Uid == data.Up_author).SingleOrDefault()?.Uname;
            data.children = children.OrderByDescending(d=>d.value);

            return Result(1, "ok", data);
        }
        /// <summary>
        /// 修改字典类型
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Up_Dic(Dic_Request_Dto dto)
        {
            var dic= await _dic_IOC._dictionary_Type_EFCore.QueryAll(d=>d.DtId==dto.id).SingleAsync();

            dic.DtName = dto.name;
            dic.DtValue=dto.value;
            dic.DtKey = dto.key;
            dic.DtUpdateAuthor = dto.Up_author;
            _dic_IOC._dictionary_Type_EFCore.Update(dic);
            var result= await _dic_IOC._dictionary_Type_EFCore.SaveChangesAsync();

            return Result(1,"修改成功");
        }
    }
}
